# coding: utf-8
from random import choice

from PySide6.QtCore import Qt, Signal, QPoint
from PySide6.QtGui import QMouseEvent, QColor
from PySide6.QtWidgets import QFrame, QVBoxLayout, QSizePolicy, QHBoxLayout
from qfluentwidgets import setFont, Action
from qfluentwidgets.components.material import AcrylicMenu, AcrylicToolTipFilter

from common import signalBus, Icon
from common.server import VideoModel
from ..widgets import ZoomImageLabel, TagLabel, BodyLabel

cover_list = [
    'https://image-assets.soutushenqi.com/moment/1756718995280_nrzw.jpg',
    'https://gd-hbimg.huaban.com/cd468116ec7cfcb0ced642ed54e595450891d7ae5a373c-rPLyWg_fw480',
    'http://hbimg.huaban.com/0886d78c60620a78c203f8f7bcca3e138b361c00697e0-Ee99vi_fw320',
    'https://image-assets.soutushenqi.com/moment/1756718995280_nrzw.jpg?x-tos-process=image/resize,w_480',
    'https://image-assets.soutushenqi.com/moment/1756718990633_dcyw.png?x-tos-process=image/resize,w_480'
]


class VideoCard(QFrame):
    clicked = Signal(object)
    finished = Signal(object)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.isMin = False

        self.verticalLayout = QVBoxLayout(self)
        self.coverLabel = ZoomImageLabel(self)
        self.titleLabel = BodyLabel('视频名称', self)
        self.descLabel = BodyLabel('视频描述', self)
        self.tagLayout = QHBoxLayout(self.coverLabel)

        self.__initWidgets()

    def __initWidgets(self):
        self.coverLabel.setScaledContents(True)
        self.coverLabel.setRadius(5)
        self.coverLabel.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        self.titleLabel.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        setFont(self.descLabel, 12)
        self.setMinimumSize(250, 200)
        self.installEventFilter(AcrylicToolTipFilter(self))

        self.__initLayout()
        self.__connectSignals()

    def __initLayout(self):
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.tagLayout.setSpacing(6)
        self.tagLayout.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignBottom)
        self.descLabel.setTextColor(QColor(0, 0, 0, 150), QColor(255, 255, 255, 150))

        self.verticalLayout.addWidget(self.coverLabel)
        self.verticalLayout.addWidget(self.titleLabel)
        self.verticalLayout.addWidget(self.descLabel)

    def __connectSignals(self):
        self.clicked.connect(self._onClicked)
        self.coverLabel.finished.connect(lambda obj: self.finished.emit(self))
        self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.customContextMenuRequested.connect(self._showContextMenu)

    def _showContextMenu(self, pos: QPoint):
        menu = AcrylicMenu(parent=self)
        menu.addAction(
            Action(Icon.CLOUD_DOWNLOAD, '下载', self, triggered=lambda: signalBus.downloadSig.emit(self.getData())))
        menu.exec(self.mapToGlobal(pos))

    def getData(self):
        title = self.property('title')
        cover_url = self.property('cover_url')
        tags = self.property('tags')
        description = self.property('description')
        vodid = self.property('vodid')
        return VideoModel(
            title=title,
            cover_url=cover_url,
            vod_id=vodid,
            is_mini=self.isMin,
            tags=tags,
            description=description
        )

    def _onClicked(self, obj):
        model = self.getData()
        signalBus.videoUrlChanged.emit(model)
        # qevent_manager.addSqlTaskToPool(
        #     add_history,
        #     '',
        #     model.title,
        #     model.cover_url,
        #     model.tags,
        #     model.description,
        #     False
        # )

    def mouseReleaseEvent(self, event: QMouseEvent):
        pos = event.position().toPoint()
        if event.button() == Qt.MouseButton.LeftButton and self.rect().contains(pos):
            self.clicked.emit(self)
        super().mouseReleaseEvent(event)

    def isNull(self):
        return self.coverLabel.isNull()

    def scaledToWidth(self, width: int):
        if self.isNull():
            return
        image = self.coverLabel.image
        h = int(width / image.width() * image.height())
        self.coverLabel.setMinimumSize(width, h)
        self.setMinimumSize(width, h + 50)

    def setMin(self, isMin: bool):
        self.isMin = isMin

    def setData(self, data: dict):
        # cover_url = data.get('coverpic', '')
        cover_url = choice(cover_list)

        title = data.get('title', '')
        self.setToolTip(title)
        self.titleLabel.setText(title)
        self.coverLabel.setUrl(cover_url)
        tags = data.get('tags', [])
        n_tags = []
        for tag in tags[:5]:
            tagLabel = TagLabel()
            tagname = tag.get('tagname', '')
            tagLabel.setText(tagname)
            n_tags.append(tagname)
            self.tagLayout.addWidget(tagLabel)
        duration = data.get('duration', '')
        scorenum = data.get('scorenum', '')
        self.descLabel.setText(f'时长：{duration}   评分：{scorenum}')

        self.setProperty('title', title)
        self.setProperty('cover_url', cover_url)
        self.setProperty('tags', ','.join(n_tags))
        self.setProperty('description', self.descLabel.text())
        self.setProperty('vodid', data['vodid'])
